import { observable, action, useStrict, computed, asMap, toJS } from 'mobx';
import BaseStore from './BaseStore';
import * as API from '../apis/nextNodeOperator'
import { Form, RouteLayout, ListPage } from 'weaver-mobile-page';
import { _ } from '../util/pcPublic';
import { Bubble, Tools } from 'weaver-mobile'
import * as Common from '../util/common'
const getLabel = Tools.getLabel;


export class NextNodeOperator extends BaseStore {
    defaultnodeids = "";
    selectedNodeId = "";
    preNextNodeIds = "";
    conditioninfo = {};
    resultDatas = {};
    canSubmit = "-4";
    nodeAttribute = "";
    branchNodesMap = {};
    mustPassNodeIds = [];//分叉起始点指定流转时，必须通过的分支第一个中间点
    doSubmitReady = () => { }
    @observable nodeInfo = [];
    @observable nodeInfoMap = {};
    @observable nextNodeParams = {};
    @observable form = new Form.Store({ route: '/req/nextNodeOperator' });
    @observable list = new ListPage.Store();
    @observable layout = new RouteLayout.Store({ route: '/req/nextNodeOperator', id: "selectNextNode" });
    @observable operatorChangeDisable = "";
    @observable groupList = [];

    needDefaultNode = '1';// 是否需默认选中下一节点
    needDefaultoperator = '1';// 是否需要带出默认操作者
    cancelFunc;

    setCancelFunc = (func) => {
        this.cancelFunc = func;
    }

    reset = () => {
        this.defaultnodeids = "";
        this.selectedNodeId = "";
        this.conditioninfo = {};
        this.resultDatas = {};
        this.nodeInfo = [];
        this.nextNodeParams = {};
        this.form = new Form.Store({ route: '/req/nextNodeOperator' });
        this.list = new ListPage.Store();
        this.layout = new RouteLayout.Store({ route: '/req/nextNodeOperator', id: "selectNextNode" });
    }

    getSelectNextFlowCondition = (params = {}) => {
        API.getSelectNextFlowCondition(params).then(result => {
            const { conditioninfo = [] } = result;
            conditioninfo.map(item => {
                if (item.domkey[0] === "nodeOperator") {
                    item.browserConditionParam.viewAttr = 3;
                    item.viewAttr = 3;
                }
                if(result.operatorChangeDisable == 1 && (item.domkey[0] === "nodeOperator" || item.domkey[0] === "ccOperator")) {
                    item.browserConditionParam.viewAttr = 1;
                    item.viewAttr = 1;
                }
            })
            this.operatorChangeDisable = result.operatorChangeDisable;
            this.conditioninfo = conditioninfo;
            this.nodeAttribute = result.nodeattribute;
            this.needDefaultNode = result.needDefaultNode;
            this.needDefaultoperator = result.needDefaultoperator;
            // this.form.initForm(conditioninfo, '/req/nextNodeOperator');
            this.getSelectFlowNodeInfo(params);
        })
    }
    getSelectFlowNodeInfo = (params = {}) => {
        API.getSelectFlowNodeInfo(params).then(result => {
            const { nodeInfo = [], branchNodesMap, mustPassNodeIds = [] } = result;
            this.branchNodesMap = branchNodesMap;
            this.mustPassNodeIds = mustPassNodeIds;

            let newDefaultnodeids = '';
            let nodeAttributes = [];

            if (nodeInfo.length > 0) {
                nodeInfo.map(node => {

                    //需过滤不在可选择范围中的节点
                    if(("," + this.selectedNodeId + ",").indexOf(node.id) > -1) {
                        newDefaultnodeids += "," + node.id;
                        if(nodeAttributes.indexOf(node.nodeAttribute) == -1) {
                            nodeAttributes.push(node.nodeAttribute)
                        }
                    }

                    let operatorsstr = "";
                    if (node.operators && node.operators.length > 0) {
                        node.operators.map(item => {
                            let name = item.name;
                            if (item.agent) {
                                name = name + "->" + item.agent.name;
                            }
                            operatorsstr += "，" + name;
                        })
                    } else {
                        operatorsstr = node.operatorGroupStr
                    }
                    if (operatorsstr.includes("，")) {
                        operatorsstr = operatorsstr.slice(1, operatorsstr.length);
                    }
                    node.operatorsstr = operatorsstr;
                    this.nodeInfoMap[node.key] = node;
                })
            }

            if(newDefaultnodeids != '') {
                newDefaultnodeids = newDefaultnodeids.substring(1);
                //默认下一节点有多个，且节点属性不全为分叉中间点，视为不合法数据，不显示默认节点
                if(nodeAttributes.length > 1 || (newDefaultnodeids.split(',').length > 1 && nodeAttributes.length == 1 && nodeAttributes[0] != '2')) {
                    newDefaultnodeids = '';
                }

                //非分叉起始点，且下一节点有多个，不显示默认节点
                if(this.nodeAttribute != '1' && newDefaultnodeids.split(',').length > 1) {
                    newDefaultnodeids = '';
                }
            }

            if(this.needDefaultNode == '1') {
                this.selectedNodeId = newDefaultnodeids;
                this.defaultnodeids = newDefaultnodeids;
            } else {// 如果未设置自动带出节点，则清空
                this.selectedNodeId = '';
                this.defaultnodeids = '';
            }

            this.nodeInfo = nodeInfo;//是一个数组
            this.list.setState({ data: nodeInfo })
            this.getDefaultDatas();
        });
    }

    //初始化表单相关信息
    processGroupListInfo = () => {

        this.groupList = [];
        
        if (this.nodeAttribute != '1') { // 不是分叉起始点
            let conditioninfo = _.cloneDeep(toJS(this.conditioninfo));
            let nodeInfo = this.nodeInfoMap[this.selectedNodeId] || {};
            conditioninfo.map((condition) => {
                this.appendHrmSqlWhere(condition, nodeInfo);
                if (condition.domkey != 'nextNode') {
                    condition.domkey = [`${condition.domkey}_${0}`];
                }
            });
            this.groupList[0] = { items: conditioninfo, defaultshow : true };
        } else { // 分叉起始点
            // 基本信息group
            this.groupList[0] = { title: getLabel(1361, '基本信息'), items: [_.cloneDeep(toJS(this.conditioninfo)[0])], defaultshow : true };
            // 每个选中节点的group
            this.selectedNodeId && this.selectedNodeId.split(',').map((nodeId, index) => {
                let nodeInfo = this.nodeInfoMap[nodeId] || {};
                let nodeName = nodeInfo.nodeName ? nodeInfo.nodeName : '';
                let conditions = _.cloneDeep(toJS(this.conditioninfo));
                // 过滤“下一节点”item
                conditions = conditions.filter(item => item.domkey[0] != 'nextNode');
                conditions.map((condition) => {
                    this.appendHrmSqlWhere(condition, nodeInfo);
                    condition.domkey = [`${condition.domkey}_${index}`];
                });
                this.groupList[index + 1] = { title: `${getLabel(15586, '节点')}：${nodeName}`, items: conditions, defaultshow : true };
            });
        }
        this.form = new Form.Store({ route: '/req/nextNodeOperator' });
        this.form.initForm(this.groupList, '/req/nextNodeOperator');
    }

    appendHrmSqlWhere = (condition, nodeInfo) => {
        //传入对应节点操作者范围
        if(condition.domkey == 'nodeOperator' || condition.domkey == 'ccOperator') {
            if(nodeInfo && nodeInfo.hrmSqlWhere) {
                condition.browserConditionParam.completeParams['sqlwhere'] = nodeInfo.hrmCompleteSqlWhere;
                condition.browserConditionParam.dataParams['sqlwhere'] = nodeInfo.hrmSqlWhere;
            }
        }
    }

    getDefaultDatas = () => {
        this.setNextNodeParams();
        this.list.setState({ selectedRowKeys: this.defaultnodeids ? this.defaultnodeids.split(',') : [] });
    }

    setdefaultnodeids = (val = "") => {

        if (val.startsWith(',')) {
            val = val.substring(1, val.length);
        }
        if (val.endsWith(',')) {
            val = val.substring(0, val.length - 1);
        }

        this.preNextNodeIds = this.selectedNodeId;
        this.defaultnodeids = val;
        this.selectedNodeId = val;
    }

    setNextNodeParams = () => {

        //获取修改下一节点之前，记录的表单值
        let preFormDatas = {};
        let preNextNodeIdArray = this.preNextNodeIds.split(',');
        if(this.form) {
            preFormDatas = toJS(this.form.formData);
        }

        this.processGroupListInfo();

        let params = {};
        this.selectedNodeId && this.selectedNodeId.split(',').map((nextNodeId, index) => {
            const val = this.nodeInfoMap[nextNodeId];
            const { nodeName = "", ccOperators = [], id = "", operators = [], operatorGroupStr = "", signType="1", ccSignType } = val; //ccOperators抄送人,sygnType会签关系，ccSignType意见选择,operators操作者，如果操作者为空，则用operatorGroupStr操作组名称

            let preIndex = preNextNodeIdArray.indexOf(nextNodeId);
            if(preIndex >= 0) {//之前已选择的节点，使用已修改的值
                params[`nodeOperator_${index}`] = preFormDatas[`nodeOperator_${preIndex}`];
                params[`ccOperator_${index}`] = preFormDatas[`ccOperator_${preIndex}`];
                params[`SignType_${index}`] = preFormDatas[`SignType_${preIndex}`];
                params[`canSubmit_${index}`] = preFormDatas[`canSubmit_${preIndex}`];
            } else {
                if (operators.length > 0 && this.needDefaultoperator == '1') {
                    let arr = [];
                    operators.map(item => {
                        arr.push({ id: item.id, name: item.name })
                    })
                    params[`nodeOperator_${index}`] = { value: arr };//节点操作者
                } else {
                    params[`nodeOperator_${index}`] = { value: [] };//节点操作者
                }
                params[`SignType_${index}`] = { value: signType };//会签关系
                if (ccOperators.length > 0 && this.needDefaultoperator == '1') {
                    let arr = [];
                    ccOperators.map(item => {
                        arr.push({ id: item.id, name: item.name })
                    })
                    params[`ccOperator_${index}`] = { value: arr };//抄送人
                } else {
                    params[`ccOperator_${index}`] = { value: [] };//抄送人
                }
                this.canSubmit = ccSignType;
                params[`canSubmit_${index}`] = { value: ccSignType };//意见选择
            }
            this.nextNodeParams = params;
            this.form.updateFields(params);
            this.setResultData({ ...params })
        });
        return params;
    }

    clearFormData = () => {
        let formData = {};
        this.processGroupListInfo();
        this.setResultData({ ...formData });
        this.nextNodeParams = formData;
        this.selectedNodeId = "";
        this.list.setState({ selectedRowKeys: [] });
        return formData;
    }
    setResultData = (state = {}) => {
        const keys = Object.keys(state);
        keys.forEach(key => {
            this.resultDatas[key] = state[key]
        })
    }

    setDoSubmitReady = (fun) => {
        if (typeof fun === "function") {
            this.doSubmitReady = fun;
        }
    }

    @action
    getResultParams = () => {
        let result = {};
        let formParams = this.form.formParams;
        let formDatas = this.form.formData;
        result.selectNodeFlow_nodeIds = this.selectedNodeId;

        this.selectedNodeId && this.selectedNodeId != '' && this.selectedNodeId.split(',').map((nextNodeId, index) => {
            result[`SignType_${index}`] = formParams[`SignType_${index}`];
            result[`canSubmit_${index}`] = this.resultDatas[`canSubmit_${index}`].value ? this.resultDatas[`canSubmit_${index}`].value:"-4";
            result[`ccOperator_${index}`] = formParams[`ccOperator_${index}`];
            result[`selectNodeFlow_operator_${index}`] = formParams[`nodeOperator_${index}`];
            result[`nodeOperator_${index}`] = formParams[`nodeOperator_${index}`];
            this.nodeInfo.map(item => {
                if (item.id === nextNodeId) {
                    result[`selectNodeFlow_nodeId_${index}`] = item.id + "_" + item.nodeType + "_" + item.nodeAttribute;
                }
            })
        })

        if(this.operatorChangeDisable == '1') {//不可修改操作者，指定流转为选择节点模式，操作者由后台计算
            result['selectNextFlowMode'] = 2;
        } else {//前台用户指定节点和操作者
            result['selectNextFlowMode'] = 1;
        }

        return result;
    }
    verification = (result, Fun) => {
        let canSubmit = true;

        if(this.selectedNodeId == '') {
            Bubble.warning(getLabel(500277,'下一节点不能为空'), 2);
            return;
        }

        this.operatorChangeDisable != '1' && this.selectedNodeId && this.selectedNodeId.split(',').map((nextNodeId, index) => {
            if (result[`selectNodeFlow_operator_${index}`] === "" || result[`selectNodeFlow_operator_${index}`] === null) {
                Bubble.warning(getLabel(500280,'下一节点操作者不能为空'), 2);
                canSubmit = false;
            }
        });

        let checkNodeIds = this.selectedNodeId.split(',');
        //分叉起始点，指定流转不是主干节点的情况下，检查是否选择了必须经过的分支
        if(this.nodeAttribute == '1' && !(checkNodeIds.length == 1 && this.nodeInfoMap[checkNodeIds[0]].nodeAttribute != '2')) {
            let mustPassCheck = true;
            this.mustPassNodeIds.map(id => {
                if(!this.checkSameElement(checkNodeIds, this.branchNodesMap[id])) {
                    mustPassCheck = false;
                }
            })
            if(!mustPassCheck) {
                Bubble.warning(getLabel(528903,"请选择必须通过的分支上的节点"), 2);
                canSubmit = false;
            }
        }
        //分叉中间点指定流转到 主干节点
        if(this.nodeAttribute == '2' && checkNodeIds.length == 1 && this.nodeInfoMap[checkNodeIds[0]].nodeAttribute < 2) {
            Common.showConfirm({
                title: getLabel(528904,"指定流转到主干节点将使流程在目前所在所有分支都变成已办，是否确认？"),
                okEvent: () => {
                    canSubmit && typeof Fun === 'function' && Fun();
                }
            });
        } else {
            canSubmit && typeof Fun === 'function' && Fun()
        }
    }

    //检查两个列表是否有共同的元素
    checkSameElement = (nodeList, checkList) => {
        let result = false;
        checkList && checkList.map(v1 => {
            if(nodeList && nodeList.indexOf(v1) > -1) {
                result = true;
            }
        })
        return result;
    }
}